<template>
  <el-dialog
    :visible="visible"
    @close="handleClose"
    :title="$t('operator.updateEmail')"
    width="30%"
  >
    <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="dataForm">
      <el-form-item :label="$t('common.email')" prop="email">
        <el-input
          v-model="dataForm.email"
          :placeholder="$t('common.email')"
          maxlength="120"
          @blur="() => (dataForm.email = dataForm.email.trim())"
          clearable
        ></el-input>
      </el-form-item>

      <div align="center" style="margin: 30px 0 10px 0">
        <span>
          <el-button size="small" type="danger" @click="cancel()">{{
            $t('common.cancel')
          }}</el-button>
          <el-button
            type="primary"
            size="small"
            :loading="updateEmailLoading"
            @click="updateEmailHandle()"
            >{{ $t('common.confirm') }}</el-button
          >
        </span>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { updateOperatorEmail } from '@/api/operator'

export default {
  data() {
    return {
      visible: false,
      updateEmailLoading: false,
      operatorId: 0,
      dataForm: {
        email: ''
      },
      dataRule: {
        email: [
          {
            required: true,
            message: this.$t('common.nullInputTip'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {},
  methods: {
    init(operatorId) {
      this.visible = true
      this.operatorId = operatorId
    },
    cancel() {
      this.visible = false
      this.$emit('close')
    },
    handleClose() {
      this.dataForm.email = ''
      this.visible = false
      this.updateEmailLoading = false
    },
    updateEmailHandle() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const entity = {
            email: this.dataForm.email
          }
          this.updateEmailLoading = true
          updateOperatorEmail(this.operatorId, entity)
            .then(() => {
              this.$message({
                type: 'success',
                message: this.$t('common.success')
              })
              this.cancel()
            })
            .catch((err) => {
              this.$confirmError(err)
            })
            .finally(() => {
              this.updateEmailLoading = false
            })
        }
      })
    }
  }
}
</script>
